//
//  DSMainTabBar.swift
//  weibo
//
//  Created by apple on 16/7/18.
//  Copyright © 2016年 小环. All rights reserved.
//

import UIKit

class DSMainTabBar: UITabBar {

    //创建闭包，点击撰写按钮调用
    var composeClosure:(()->())?
    
    //懒加载撰写按钮
    lazy var composeButton:UIButton={
        let comBtn=UIButton()
        //添加背景图片
        comBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        comBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //添加图片
        comBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        comBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //绑定事件源
        comBtn.addTarget(self, action: "clickComBtn", forControlEvents: UIControlEvents.TouchDown)
        
        //添加到控制器
        self.addSubview(comBtn)
        return comBtn
    }()
    
    //布局tabBar
    private let buttonCount=5
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //计算每个tabBarItem的宽度
        let width=bounds.width / CGFloat(buttonCount)
        
        //创建每个item的frame
        let frame=CGRectMake(0, 0, width, bounds.height)
        
        var index=0
        //遍历子控制器
        for item in subviews{
            //判断是否是button
            let cls=NSClassFromString("UITabBarButton")
            //强制拆包并判断
            if item.isKindOfClass(cls!){
                item.frame=CGRectMake(CGFloat(index) * width, 0, width, frame.height)
                //留出第二个位置给撰写按钮
                index++
                if index==2{
                    index++
                }
            }
        }
        
        //设置撰写按钮到中间的位置
        composeButton.frame=CGRectMake(2*width, 0, width, frame.height)
    }
    
    //:MARK - 事件源
    func clickComBtn()->Void{
        //调用闭包
        composeClosure?()
    }
}
